const schedule = require('node-schedule');
const { Op } = require('sequelize');
const moment = require('moment');
const logger = require('../../utils/logger');
const { sequelize, User } = require('../../models');

/**
 * 定时检查并处理超时未支付订单
 * 每天陵城4:30执行一次
 */
function scheduleMembershipCheck() {
  schedule.scheduleJob('0 0 30 * * *', async function () {
    console.log('订单状态任务开始执行');
    const t = await sequelize.transaction();
    try {
      // 查找超时未支付的订单
      const expiredUsers = await User.findAll({
        attributes: ['id'],
        where: {
          role: 1,
          createdAt: {
            [Op.lt]: new Date(), // 小于当前时间
          },
        },
        transaction: t,
        lock: true, // 使用排它锁，防止并发更新
      });
      // 已超时订单的ID列表
      const userIds = expiredUsers.map((order) => order.id);
      // 批量更新超时订单状态
      await User.update(
        {
          role: 0, // 将用户改为普通用户
          membershipExpiredAt: null,
        },
        {
          where: {
            id: userIds,
          },
          transaction: t,
        }
      );
      await t.commit();
    } catch (error) {
      await t.rollback();
      logger.error('会员用户定时任务处理超时订单失败', error);
    }
  });
}

module.exports = scheduleMembershipCheck;
